import React, { PureComponent } from "react";
import { connect } from "dva";
import moment from 'moment';
import { Modal, Row, Col, Form, Input, Select, Checkbox, DatePicker, Icon, Button, message} from "antd";
import Upload from "../../../components/Upload";
import RegionalSelection from "../../Form/RegionalSelection";
import SparesChoose from "./SparesChoose";
import AssodevChoose from "./AssodevChoose";


const FormItem = Form.Item;
const { Option } = Select;
const { TextArea } = Input;

const getBase64 = (img, callback) => {
  const reader = new FileReader();
  reader.addEventListener("load", () => callback(reader.result));
  reader.readAsDataURL(img);
};

const beforeUpload = file => {
  const isJPG = file.type === "image/jpeg" || file.type === "image/png";
  if (!isJPG) {
    message.error("仅允许上传JPG、PNG文件!");
  }
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    message.error("图片文件不能大于2MB!");
  }
  return isJPG && isLt2M;
};



@connect(({ equipment_integrated, global }) => ({
  baseUrl:global.baseUrl,
  loading:equipment_integrated.loading,
  detaildata:equipment_integrated.detaildata,
}))
@Form.create()
export default class EquipmentAdd extends PureComponent {
  constructor(props) {
    super(props);
    this.state={
      fileList: [] ,
      imageUrl: null,
      loading_picupload: false,
      spareChoose:[],
      assodevChoose:[],
      modalSpareChooseVisible: false,
      modalAssodevChooseVisible: false,
    }
  }

  componentDidMount() {
    // 获取所有下拉数据的datasource
    // this.props.dispatch({
    //   type: "equipment_integrated/fetch_selectsource_for_add",
    // })
  }


  componentWillReceiveProps(nextProps) {
    if (nextProps.visible === true && this.props.visible === false) {
      // this.props.dispatch({
      //   type: "system_cooperation/fetch_all_collaborate"
      // });

      // 编辑时 读取详情
      if (nextProps.detailId && nextProps.detailId !== 0) {
          this.props.dispatch({
            type: "equipment_integrated/fetch_equipment_info",
            payload: {
              devId: nextProps.detailId
            }
          })
          .then(() => {
             //根据区域id，获取点位数据
              const districtId = this.props.detaildata.districtId;
              this.props.dispatch({
                type: 'global/fetch_select_point',
                payload: {
                  districtId,
                }
              })
          })
          .then(() => {
            const {baseUrl} = this.props;
            const detaildata=this.props.detaildata;
            const spareChoose = (detaildata.deviceAttachment && detaildata.deviceAttachment.length>0) ? detaildata.deviceAttachment.map(item => Number(item.id)) : [];
            const assodevChoose = (detaildata.assodev && detaildata.assodev.length>0) ? detaildata.assodev.map(item => item.devId) : [];
            this.setState({
              fileList: this.props.detaildata.devDatum.map(item=>{
                item.url = baseUrl+item.url;
                return item;
              }),
              spareChoose,
              assodevChoose
            });
          });
      }

      if (nextProps.detailId === 0) {
        this.setState({
          fileList: [] ,
          imageUrl: null,
          loading_picupload: false,
          spareChoose:[],
          assodevChoose:[],
        });
      }

    }
  }

  handleSubmit(e) {
    e.preventDefault();
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        const { dispatch, detailId } = this.props;
        const action = detailId === 0 ? 'add' : 'edit';
        const devId = detailId === 0 ? undefined : detailId;
        let enableDate = undefined;
        if (values.enableDate) {
          enableDate = values.enableDate.unix() * 1000;
        }

        if(values.region && values.region.pointId!==0 && values.region.districtId.length>0){
          values.districtId = values.region.districtId[values.region.districtId.length - 1];
          values.pointId = values.region.pointId;
        }

        dispatch({
            type: `equipment_integrated/${action}_equipment`,
            payload: {
              ...values,
              enableDate,
              devId,
              region:undefined,

            }
          })
          .then(() => {
            this.handleReset();
            this.handleCancel();
            this.props.callback();
          });
      }
    });
  }

  handleReset = () => {
    this.setState({
      fileList: [],
      imageUrl: null,
    })
    this.props.form.resetFields();
  };

  handleCancel = () => {
    this.handleReset();
    this.props.onCancel(false);
  };


  initArrObject = (arr, name) => {
    if (arr) {
      let str = [];
      for (let i of arr) {
        str.push(i[name]);
      }
      return str.join("、");
    }
  };

  // 单图上传时间
  handleChangePicUpload = info => {
    if (info.file.status === "uploading") {
      this.setState({ loading: true });
      return;
    }
    let file = null;
    if (info.file.status === "done") {
      // Get this url from response in real world.
      // info.fileList.splice(0,info.fileList.length-1);
      getBase64(info.file.originFileObj, imageUrl =>
        this.setState({
          imageUrl,
          loading_picupload: false
        })
      );
    }
  };

  uploadPic = e => {
    let file_url=null;
    if (e.file.status === "done" && e.file.response && e.file.response.data && e.file.response.data.token) {
      file_url = e.file.response.data.token;
    }
    return file_url;
  };


  // 多文件上传
  uploadFile = e => {
    if (Array.isArray(e)) {
      return e;
    }
    const filelist =
      e &&
      e.fileList.reduce((arr, current) => {
        if (
          current.response &&
          current.response.data &&
          current.response.data.token
        ) {
          return arr.concat(current.response.data.token);
        } else {
          if (current.status && current.status === "error") {
            return arr.concat([]);
          } else {
            return arr.concat(current.uid);
          }
        }
      }, []);
    return filelist;
  };

  handleUploadFiles = info => {
    const { detailId } = this.props;
    let fileList = info.fileList;
    if(fileList.length > 2){
      message.error("最多只能上传两个文件")
      return false
    }

    if (info.file.status == "done") {
      //const filename_str = info.file.name.split(".");
      // this.props.form.setFieldsValue({
      //   project_name: filename_str[0]
      // });

      fileList = fileList.map(item => {
        if (item.response && item.response.error_no != "0") {
          item.status = "error";
        }
        return item;
      });
    }

    this.setState({ fileList });
  };

  handleRemoveUploadFiles = file => {};

  // 安装点位事件-------------------------------------
  handleSearchDistrict = ( value ) =>{
    const { dispatch } = this.props;
    const districtId=value.districtId[value.districtId.length-1];
    const pointId=value.pointId;
    const loadPoint=value.loadPoint;
    if(pointId===0){
      // 清空子节点操作
      dispatch({
        type: 'global/fetch_clear_point',
      })
    }

    if(loadPoint && districtId!=0){

      dispatch({
        type: 'global/fetch_select_point',
        payload: {
          districtId,
        },
      })
    }
  }
  // 用最后个点位检索成数组
  formatDistrictData = (lastid) =>{
    const district=[];
    if(lastid){
      district.unshift(lastid);
      const {selectSource: {districtData} } = this.props;
      const now = districtData.find(item=>item.districtId===lastid);
      if(now && now.parentId!="0"){
        district.unshift(now.parentId);
        this.formatDistrictDataSec(district,now.parentId);
      }
    }
    return district;
  }
  formatDistrictDataSec = (arr,id) =>{
    const {selectSource: {districtData} } = this.props;
    const now = districtData.find(item=>item.districtId===id);
    if(now && now.parentId!="0"){
      arr.unshift(now.parentId);
      this.formatDistrictDataSec(arr,now.parentId);
    }
    return arr;
  }
  checkDistrict =  (rule, value, callback) => {
    if (value.pointId!==0) {
      callback();
      return;
    }
    callback('请选择区域点位!');
  }



  // upLoadListFormat = (data) => {
  //   if(data && data.length>0){
  //     return data.map((item,index)=>{
  //       const temparray = item.split("/");
  //       return {
  //         uid:index,
  //         name:temparray[temparray.length-1],
  //         url:item,
  //       };
  //     })
  //   }else{
  //     return []
  //   }
  //
  // }

  // 显示选择备件弹窗
  handleSparesChooseModalVisible= flag => {
    this.setState({
      modalSpareChooseVisible: !!flag,
    });
  };

  // 备件点选选择后数据返回父级
  handleSparesChoose = (value) =>{
    const { form: { setFieldsValue }} = this.props;
    this.setState({
      spareChoose:value,
    });
    setFieldsValue({ deviceAttachment: value });

  }

  // 显示选择关联设备弹窗
  handleAssodevChooseModalVisible= flag => {
    this.setState({
      modalAssodevChooseVisible: !!flag,
    });
  };

  // 显示选择关联设备弹窗
  handleAssodevChoose = (value) =>{
    const { form: { setFieldsValue }} = this.props;
    this.setState({
      assodevChoose:value.map(e=>e.devId),
    });
    setFieldsValue({ assodevId: value.map(e=>e.devId) });

  }

  render() {
    const { visible, loading, detailId, detaildata, selectSource, dictionaries, baseUrl } = this.props;
    const { imageUrl, modalSpareChooseVisible, modalAssodevChooseVisible, spareChoose, assodevChoose } = this.state;
    const { getFieldDecorator } = this.props.form;

    const formItemLayout = {
      labelCol: { span: 8 },
      wrapperCol: { span: 16 }
    };



    const uploadButton = (
      <div>
        <Icon type={this.state.loading_picupload ? "loading" : "plus"} />
        <div className="ant-upload-text">上传</div>
      </div>
    );



    return (
      <div>
        <Modal
          title={detailId === 0 ? "新增设备" : "编辑设备"}
          okText={detailId === 0 ? "提交" : "编辑"}
          visible={visible}
          onOk={this.handleSubmit.bind(this)}
          confirmLoading={loading.model_submit}
          onCancel={this.handleCancel}
          width={900}
        >
          <Form layout="horizontal">
            <Row gutter={24}>
              <Col span={8}>
                <FormItem {...formItemLayout} label="设备名称" colon={false}>
                  {getFieldDecorator("devName", {
                    initialValue: detailId === 0 ? undefined : detaildata.devName,
                    rules: [
                      { required: true, message: "请输入设备名称" },
                    ]
                  })(
                    <Input placeholder="请输入设备名称" />
                  )}
                </FormItem>
              </Col>
              <Col span={8}>
                <FormItem {...formItemLayout} label="外部编号" colon={false}>
                  {getFieldDecorator("externalCode", {
                    initialValue: detailId === 0 ? undefined : detaildata.externalCode,
                    rules: [
                      // { required: true, message: "请输入设备名称" },
                    ]
                  })(
                    <Input placeholder="请输入外部编号" />
                  )}
                </FormItem>
              </Col>
              <Col span={8}>
                <FormItem {...formItemLayout} label="设备编号" colon={false}>
                  {getFieldDecorator("devCode", {
                    initialValue: detailId === 0 ? undefined : detaildata.devCode,
                    rules: [
                      // { required: true, message: "请输入设备名称" },
                    ]
                  })(
                    <Input placeholder="请输入设备编号" />
                  )}
                </FormItem>
              </Col>
              <Col span={8}>
                <FormItem {...formItemLayout} label="RFID编号" colon={false}>
                  {getFieldDecorator("rfidCode", {
                    initialValue: detailId === 0 ? undefined : detaildata.rfidCode,
                    rules: [
                      // { required: true, message: "请输入设备名称" },
                    ]
                  })(
                    <Input placeholder="请输入RFID编号" />
                  )}
                </FormItem>
              </Col>


              <Col span={8}>
                <FormItem {...formItemLayout} label="设备型号" colon={false}>
                  {getFieldDecorator("devModel", {
                    initialValue: detailId === 0 ? undefined : detaildata.devModel,
                    rules: [
                      // { required: true, message: "请输入设备名称" },
                    ]
                  })(
                    <Input placeholder="请输入设备型号" />
                  )}
                </FormItem>
              </Col>

              <Col span={8}>
                <FormItem {...formItemLayout} label="设备类型" colon={false}>
                  {getFieldDecorator("devType", {
                    initialValue: detailId === 0 ? undefined : (detaildata.devType && detaildata.devType),
                    rules: [
                      // { required: true, message: "请输入设备名称" },
                    ]
                  })(
                    <Select placeholder="请选择设备类型"
                            getPopupContainer={triggerNode => triggerNode.parentNode}
                            style={{ width: '100%' }}>
                      {dictionaries.deviceType && dictionaries.deviceType.map(item => (
                        <Option key={item.value} value={item.value}>{item.label}</Option>
                      ))}
                    </Select>
                  )}
                </FormItem>
              </Col>

              <Col span={8}>
                <FormItem {...formItemLayout} label="设备参数" colon={false}>
                  {getFieldDecorator("devParam", {
                    initialValue: detailId === 0 ? undefined : detaildata.devParam,
                    rules: [
                      // { required: true, message: "请输入设备名称" },
                    ]
                  })(
                    <Input placeholder="请输入设备参数" />
                  )}
                </FormItem>
              </Col>

              <Col span={8}>
                <FormItem {...formItemLayout} label="设备寿命" colon={false}>
                  {getFieldDecorator("devLife", {
                    initialValue: detailId === 0 ? undefined : (detaildata.devLife && detaildata.devLife),
                    rules: [
                      // { required: true, message: "请输入设备名称" },
                    ]
                  })(
                    <Select placeholder="请选择设备寿命"
                            getPopupContainer={triggerNode => triggerNode.parentNode}
                            style={{ width: '100%' }}>
                      {dictionaries.deviceLife && dictionaries.deviceLife.map(item => (
                        <Option key={item.value} value={item.value}>{item.label}</Option>
                      ))}
                    </Select>
                  )}
                </FormItem>
              </Col>

              <Col span={8}>
                <FormItem {...formItemLayout} label="关联设备" colon={false}>
                  {getFieldDecorator("assodevId", {
                    initialValue: detailId === 0 ? undefined : detaildata.assodev && detaildata.assodev.length>0 ? detaildata.assodev.map(item => item.devId) : undefined,
                    rules: [
                      // { required: true, message: "请输入设备名称" },
                    ]
                  })(
                    <Input type="hidden"/>
                  )}
                  <Button
                    onClick={() => this.handleAssodevChooseModalVisible(true)}
                    type="default"
                  >
                    {assodevChoose.length>0 ? `已选${assodevChoose.length}项` : '选择'}
                  </Button>
                </FormItem>
              </Col>
              <Col span={8}>
                <FormItem {...formItemLayout} label="附属备件" colon={false}>
                  {getFieldDecorator("deviceAttachment", {
                    initialValue: detailId === 0 ? undefined : (detaildata.deviceAttachment && detaildata.deviceAttachment.length>0 ? detaildata.deviceAttachment.map(item => Number(item.id)) : undefined),
                    rules: [
                      // { required: true, message: "请输入设备名称" },
                    ]
                  })(
                    <Input type="hidden"/>
                  )}
                  <Button
                    onClick={() => this.handleSparesChooseModalVisible(true)}
                    type="default"
                  >
                    {spareChoose.length>0 ? `已选${spareChoose.length}项` : '选择'}
                  </Button>
                </FormItem>
              </Col>


              {/*
              <Col span={8}>
                <FormItem {...formItemLayout} label="维保单位" colon={false}>
                  {getFieldDecorator("maintenanceId", {
                    initialValue: detailId === 0 ? undefined : (detaildata.maintenanceId && detaildata.maintenanceId),
                    rules: [
                      // { required: true, message: "请输入设备名称" },
                    ]
                  })(
                    <Select placeholder="请选择维保单位"
                            getPopupContainer={triggerNode => triggerNode.parentNode}
                            style={{ width: '100%' }}>
                      {selectSource.maintenance && selectSource.maintenance.map(item => (
                        <Option key={item.maintenanceId} value={item.maintenanceId}>{item.maintenanceName}</Option>
                      ))}
                    </Select>
                  )}
                </FormItem>
              </Col>
              */}

              <Col span={8}>
                <FormItem {...formItemLayout} label="保养周期" colon={false}>
                  {getFieldDecorator("maintainPeriod", {
                    initialValue: detailId === 0 ? undefined : detaildata.maintainPeriod,
                    rules: [
                      // { required: true, message: "请输入设备名称" },
                    ]
                  })(
                    <Input placeholder="请输入保养周期" />
                  )}
                </FormItem>
              </Col>

              <Col span={8}>
                <FormItem {...formItemLayout} label="启用时间" colon={false}>
                  {getFieldDecorator("enableDate", {
                    initialValue: detailId === 0 ? undefined : (detaildata.enableDate && moment(Number(detaildata.enableDate))),
                  })(
                    <DatePicker
                      placeholder="请输入启用时间"
                      style={{ width: "100%" }}
                    />
                  )}
                </FormItem>
              </Col>


              <Col span={8}>
                <FormItem {...formItemLayout} label="品牌" colon={false}>
                  {getFieldDecorator("trademark", {
                    initialValue: detailId === 0 ? undefined : detaildata.trademark,
                    rules: [
                      // { required: true, message: "请输入设备名称" },
                    ]
                  })(
                    <Input placeholder="请输入品牌" />
                  )}
                </FormItem>
              </Col>


              <Col span={8}>
                <FormItem {...formItemLayout} label="供货商" colon={false}>
                  {getFieldDecorator("supplier", {
                    initialValue: detailId === 0 ? undefined : detaildata.supplier,
                    rules: [
                      // { required: true, message: "请输入设备名称" },
                    ]
                  })(
                    <Input placeholder="请输入供货商" />
                  )}
                </FormItem>
              </Col>

              <Col span={8}>
                <FormItem {...formItemLayout} label="设备管理员" colon={false}>
                  {getFieldDecorator("adminUserId", {
                    initialValue: detailId === 0 ? undefined : detaildata.adminUserId,
                    rules: [
                      // { required: true, message: "请输入设备名称" },
                    ]
                  })(
                    <Select placeholder="请选择设备管理员"
                            getPopupContainer={triggerNode => triggerNode.parentNode}
                            style={{ width: '100%' }}>
                      {selectSource.adminUser && selectSource.adminUser.map(item => (
                        <Option key={item.userId} value={item.userId}>{item.realName}</Option>
                      ))}
                    </Select>
                  )}
                </FormItem>
              </Col>

              <Col span={8}>
                <FormItem {...formItemLayout} label="备注" colon={false}>
                  {getFieldDecorator("remarks", {
                    initialValue: detailId === 0 ? undefined : detaildata.remarks,
                    rules: [{ max: 200, message: "不超过200个字" }]
                  })(
                    <TextArea
                      placeholder="请输入备注内容"
                      autosize={{ minRows: 1, maxRows: 6 }}
                    />
                  )}
                </FormItem>
              </Col>

              <Col span={16}>
                <FormItem labelCol={{ span: 4 }} wrapperCol={{ span: 20 }}  label="区域点位" colon={false} >
                  {getFieldDecorator('region',{
                    initialValue: detailId === 0 ? {districtId:[],pointId:0} : {districtId:this.formatDistrictData(detaildata.districtId),pointId:detaildata.pointId},
                    rules: [{required: true, message: "请选择区域点位"},{validator: this.checkDistrict}],
                  })(
                    <RegionalSelection
                      districtData={selectSource.districtData}
                      pointData={selectSource.pointData}
                      onChange={this.handleSearchDistrict}
                    />
                  )}
                </FormItem>
              </Col>


              <Col span={8}>
                <FormItem
                  {...formItemLayout}
                  label="设备资料"
                  colon={false}
                >
                  {getFieldDecorator("devDatum", {
                    valuePropName: "file",
                    getValueFromEvent: this.uploadFile,
                  })(
                    <Upload
                      // defaultFileList={detailId === 0 ? null : detaildata.devDatum}
                      fileList={this.state.fileList}
                      onChange={this.handleUploadFiles}
                      onRemove={this.handleRemoveUploadFiles}
                    >
                      <Button>
                        <Icon type="upload" /> 上传
                      </Button>
                    </Upload>
                  )}
                </FormItem>
              </Col>


              <Col span={8} >
                <FormItem
                  {...formItemLayout}
                  label="设备图片"
                  extra={<span>支持jpg、png<br/>图片大小不超过2M</span>}
                >
                  {getFieldDecorator("devPhoto", {
                    valuePropName: "file",
                    getValueFromEvent: this.uploadPic
                  })(
                    <Upload
                      listType="picture-card"
                      className="avatar-uploader"
                      showUploadList={false}
                      beforeUpload={beforeUpload}
                      onChange={this.handleChangePicUpload}
                    >
                      {
                        detailId !== 0
                        ? detaildata.devPhoto && detaildata.devPhoto.url ? (<img src={`${baseUrl}${detaildata.devPhoto.url}`} alt="" style={{ width: 100, height: 100 }}/>) : (uploadButton)
                        : imageUrl ? (<img src={imageUrl} alt="" style={{ width: 100, height: 100 }}/>) : (uploadButton)
                      }
                    </Upload>
                  )}
                </FormItem>
              </Col>





            </Row>
          </Form>

        </Modal>

        <Modal
          title={"请选择相关附属备件"}
          visible={modalSpareChooseVisible}
          onCancel={() => this.handleSparesChooseModalVisible(false)}
          width={900}
          destroyOnClose={true}
          footer={null}
          bodyStyle={{padding:0}}
        >
          <SparesChoose
            dictionaries={dictionaries}
            selectSource={selectSource}
            selectCallBack={this.handleSparesChoose}
            spareChoose={spareChoose}
          />
        </Modal>

        <Modal
          title={"请选择关联设备"}
          visible={modalAssodevChooseVisible}
          onCancel={() => this.handleAssodevChooseModalVisible(false)}
          width={900}
          destroyOnClose={true}
          footer={null}
          bodyStyle={{padding:0}}
        >
          <AssodevChoose
            dictionaries={dictionaries}
            selectSource={selectSource}
            selectCallBack={this.handleAssodevChoose}
            assodevChoose={assodevChoose}
          />
        </Modal>

      </div>
    );
  }
}
